/*
 * File Name：BaseActivity.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： BaseActivity.java
 * Modify By：res-jxliu
 * Modify Date：2015年3月21日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.eyeguard.EyeGuardModeView;
import com.ciwong.mobilelib.i.ActivityInterface;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.ActFinishHandler.ActivityAnimationEndListener;
import com.ciwong.mobilelib.utils.BaseActivityManager;
import com.ciwong.mobilelib.utils.BaseActivityManager.ActivityInfo;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.CWUpdate;
import com.ciwong.mobilelib.utils.EAction;
import com.ciwong.mobilelib.utils.HomeListener;
import com.ciwong.mobilelib.utils.StatUtils;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;
import com.ciwong.mobilelib.widget.NewCWProgressBar;
import com.ciwong.mobilelib.widget.RelationMenu2;
import com.ciwong.mobilelib.widget.TitleBar;
import com.ciwong.mobilelib.widget.ToastTopDialog;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author res-jxlius
 * @version ciwong v.1.0 2015年3月21日
 * @since ciwong v.1.0
 */

public abstract class BaseActivity extends AppCompatActivity
        implements ActivityInterface, ActivityAnimationEndListener {
    public String TAG = getClass().getSimpleName();
    /**
     * 默认标题栏返回按钮显示字符:"返回"
     */
    public static final int DEF_GO_BACK = -1;

    /**
     * 间隔 刷新时间
     */
    public static final long REFRESH_TIME = 60 * 5000;

    /**
     * 是否销毁
     */
    protected boolean isDestroy;

    /**
     * 是否使用共用背景
     */
    private boolean useCommentBG = true;

    /**
     * 内容容器
     */
    private FrameLayout mainContainer;

    /**
     * 标题栏
     */
    protected TitleBar titleBar;

    /**
     * 返回按钮事件
     */
    private GoBackListener mGoBackListener;

    /**
     * 是否验证来源
     */
    private boolean valideSource = true;

    /**
     * activity标签， 主要用于一个activity被同时打开多次时，标志不同的activity
     */
    protected String tag = getClass().getSimpleName();

    private ActivityInfo actInfo;


    private boolean registStatistics = true;

    /**
     * 滑动结束
     */
    private boolean flingFinish = true;

    protected NewCWProgressBar progressBar;

    /**
     * 作为底层activity里是否需要右滑关闭动画
     */
    private boolean isNeedLowerActivityAniamtion = true;
    private LinearLayout ll_loading;

    private Handler mBaseHandler = new Handler();
    protected boolean isCancelToastOnPause = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //如果是8.0系统的手机，并且认为是透明主题的Activity
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            fixOrientation();
        }
        preCreate();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        initContentView();
        permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        try {
            findViews();
        } catch (NullPointerException e) {

        }
        // 点击标题事件，触发后所有listview或scrollView会滑到顶部。如果有特殊的点击标题事件，可在initEvent中覆盖此事件。
        setMiddleTextListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                scrollToTop(mainContainer);
            }
        });
        initEvent();
        init();
        loadData();
        initActivityInfo();
        addActivity();

        /**
         * 设置通用背景
         */
        if (useCommentBG) {
            View baseContainer = findViewById(R.id.activity_base_container);
            if (baseContainer != null)
                baseContainer.setBackgroundResource(R.color.main_bg_color);
        }
        initBackText();
        initBackEvent();
        saveStateCallBack(savedInstanceState);
        registListenerHome();
    }

    protected void setFlingFinish(boolean flingF) {
        flingFinish = flingF;
    }

    /**
     * 点击标题列表滑动到top
     */
    private void scrollToTop(ViewGroup container) {
        int childCount = container.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = container.getChildAt(i);
            if (view instanceof ScrollView) {
                ((ScrollView) view).smoothScrollTo(0, 0);
            } else if (view instanceof ListView) {
                ListView lv = (ListView) view;
                lv.smoothScrollToPosition(0);
            }
            if (view instanceof ViewGroup) {
                int subChildCount = ((ViewGroup) view).getChildCount();
                if (subChildCount != 0) {
                    scrollToTop((ViewGroup) view);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        checkUpdate();//只在MainActivity进行更新。

        //护眼模式打开的话，OnResume方法调用
        if (BaseApplication.getInstance().isEyeGuardPerssionGet) {
            EyeGuardModeView.showEyeGuard(true);
        }
//        StatUtils.onResume(this);
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            if (isNeedCheck) {
                showGetSDcardPermissDialog();
            }
        }
    }

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkPermissions();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkPermissions();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    protected boolean isNeedCheck = false;
    private List<String> permissionList = new ArrayList<String>();
    private Map<String, String> noteMap = new HashMap<>();
    private final int CODE_REQUEST_PERMISSION = 9900;

    public boolean isNeedCheck() {
        return isNeedCheck;
    }

    public void setNeedCheck(boolean needCheck) {
        isNeedCheck = needCheck;
    }

    /**
     * XXPermissions方法是请求某一权限，
     */
    private void checkPermissions() {
        isNeedCheck = false;
        XXPermissionTool.checkPermissions(this, //
                permissionList, //
                noteMap, //
                CODE_REQUEST_PERMISSION, //
                new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                    @Override
                    public void onCheckPermissionsFinished(int flag) {
                        if (0 == flag) {
                            isNeedCheck = true;
                        } else {
                            isNeedCheck = true;
                        }
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();

        StatUtils.onPause(this);
        if (isCancelToastOnPause) {
            ToastUtil.INSTANCE.cancelToast();//销毁页面时，取消掉toast
        }
    }

    /**
     * 需要保存activity状态时，调用
     *
     * @param saveState 保存状态
     */
    protected void saveStateCallBack(Bundle saveState) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        removeActivity();
        isDestroy = true;
        super.onDestroy();
        if (null != mHomeWatcher) {
            mHomeWatcher.stopWatch();
        }
    }

    protected void registStatistics(boolean isRegistStatistics) {
        registStatistics = isRegistStatistics;
    }

    /**
     * 设置是否使用通用背景
     *
     * @param userCommonbg 是否使用通用背景
     */
    public void setUseCommonBG(boolean userCommonbg) {
        useCommentBG = userCommonbg;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    public UserInfoBase getUserInfoBase() {
        return getBaseApplication().getUserInfoBase();
    }

    /**
     * 获取习信application
     *
     * @return 习信application
     */
    protected BaseApplication getBaseApplication() {
        return (BaseApplication) getApplication();
    }

    /**
     * 可执行数据库操作异步任务
     *
     * @param task     线程
     * @param priority 优先级{@link //ThreadTask.ThreadPeriod.PERIOD_LOW},
     *                 {@link //ThreadTask.ThreadPeriod.PERIOD_LOW},
     *                 {@link //ThreadTask.ThreadPeriod.PERIOD_HIGHT}
     */
    public void executeDBThread(Runnable task, int priority) {
        ThreadTask.getInstance().executorDBThread(task, priority);
    }

    /**
     * 可执行其它异步任务
     *
     * @param task     线程
     * @param priority //优先级{@link //ThreadTask.ThreadPeriod.PERIOD_LOW},
     *                 {@link //ThreadTask.ThreadPeriod.PERIOD_MIDDLE},
     *                 {@link //ThreadTask.ThreadPeriod.PERIOD_HIGHT}
     */
    public void executeOtherThread(Runnable task, int priority) {
        ThreadTask.getInstance().executorOtherThread(task, priority);
    }

    @Override
    public String getApplicationTag() {
        return getBaseApplication().getAppTag();
    }

    @Override
    public void setTag(String actTag) {
        this.tag = actTag;
    }

    @Override
    public String getTag() {
        return tag;
    }

    /**
     * 根据activity的名字和tag获取activity
     *
     * @param clsName activity名字
     * @param t       tag
     * @return 想要获取的activity
     */
    public Activity getActivity(String clsName, String t) {
        ActivityInfo activity = BaseActivityManager.getInstance()
                .getActivity(clsName, t);
        if (activity != null) {
            return activity.getActivity();
        }
        return null;
    }

    /**
     * 设置是否验证来源
     *
     * @param valide
     */
    public void setValideSource(boolean valide) {
        this.valideSource = valide;
    }

    private void initBackEvent() {
        if (titleBar != null) {
            titleBar.setBackListener(new OnClick());
        }
    }

    /**
     * 初始化返回按钮上的文字
     */
    public void initBackText() {
        Intent intent = getIntent();
        if (intent != null && titleBar != null) {
            int goBackResId = intent.getIntExtra(BaseJumpManager.GO_BACK_ID,
                    DEF_GO_BACK);
            if (goBackResId == DEF_GO_BACK) {
                hideBackBar();
            } else {
                try {
                    setBackText(goBackResId);
                } catch (Exception e) {
                    hideBackBar();
                }
            }
        }
    }

    /**
     * 隐藏标题栏
     */
    public void hideTitleBar() {
        titleBar.setVisibility(View.GONE);
    }

    public void setTitleBarDividerGone() {
        titleBar.setTitleBarDividerGone();
    }

    /**
     * 显示标题栏
     */
    public void showTitleBar() {
        titleBar.setVisibility(View.VISIBLE);
    }

    /**
     * 设置标题
     *
     * @param resid 标题
     */
    public void setTitleText(int resid) {
        titleBar.setTitle(resid);
    }

    public void setBackImg(int id) {
        if (titleBar != null) {
            titleBar.setBackImg(id);
        }
    }

    /**
     * 设置标题
     *
     * @param title 标题
     */
    public void setTitleText(String title) {
        titleBar.setTitle(title);
    }

    public String getTitleText() {
        return titleBar.getTitle();
    }

    /**
     * 设置菜单标题
     *
     * @param menuArr 菜单标题
     */
    public void setMenuTitle(String[] menuArr) {
        titleBar.setMenuTitle(menuArr);
    }

    /**
     * 动态标题
     *
     * @param text
     */
    public void setDynamicTitle(String text) {
        titleBar.setDynamicTitle(text);
    }

    /**
     * 设置右键字体及颜色
     *
     * @param text
     * @param colorRes 颜色值的资源id
     */
    public void setRightBtnText(String text, int colorRes) {
        titleBar.setRightBtnText(text, colorRes);
    }

    /**
     * 设置菜单标题的事件监听
     *
     * @param listener 事件监听
     */
    public void setMenuListener(RelationMenu2.OnSelectChangedListener listener) {
        titleBar.setMenuListener(listener);
    }

    /**
     * 隐藏左边
     */
    public void hideBackBar() {
        titleBar.hideBackBar();
    }

    /**
     * 显示返回按钮
     */
    public void showBackBar() {
        titleBar.showBackBar();
    }

    /**
     * 设置返回按钮的文字
     *
     * @param resid 标题
     */
    public void setBackText(int resid) {
        titleBar.setBackText(resid);
    }

    /**
     * 设置返回按钮的文字
     *
     * @param title 标题
     */
    public void setBackText(String title) {
        titleBar.setBackText(title);
    }

    /**
     * 设置返回按钮的字体颜色及size
     *
     * @param colorId
     * @param size    0为默认
     */
    public void setBackTextSytle(int colorId, int size) {
        titleBar.setBackTextSytle(colorId, size);
    }

    /**
     * 设置中间标题事件
     *
     * @param listener 事件监听
     */
    public void setMiddleTextListener(ViewOnClickListener listener) {
        titleBar.setMiddleTextListener(listener);
    }

    /**
     * 设置标题栏中返回按钮事件,若不设置默认操作是finish当前Activity
     *
     * @param listener {@link GoBackListener}
     */
    protected void setGoBackListener(GoBackListener listener) {
        mGoBackListener = listener;
    }

    /**
     * 显示左边的进度条
     *
     * @param text 显示的文字，null表示不显示文字
     */
    public void showLeftProgressBar(String text) {
        titleBar.showLeftProgressBar(text);
    }

    /**
     * 隐藏左边的进度条
     */
    public void hideLeftProgressBa() {
        titleBar.hideLeftProgressBar();
    }

    /**
     * 显示中间的进度条
     *
     * @param text 需要显示的文字,null表示不显示文字
     */
    public void showMiddleProgressBar(String text) {
        if (isDestroy) {
            return;
        }
        titleBar.showMiddleProgressBar(text);
    }

    /**
     * 中间的进度条是否显示中
     *
     * @return 是否显示
     */

    public boolean isShowMiddleProgressBar() {
        return titleBar.isShowMiddleProgressBar();
    }

    /**
     * 隐藏中间的进度条
     */
    public void hideMiddleProgressBar() {
        if (isDestroy) {
            return;
        }
        titleBar.hideMiddleProgressBar();
    }

    /**
     * 显示右边的进度条
     *
     * @param text 需要显示的文字,null表示不显示文字
     */
    public void showRightProgressBar(String text) {
        titleBar.showRightProgressBar(text);
    }

    /**
     * 隐藏右边的进度条
     */
    public void hideRightProgressBar() {
        titleBar.hideRightProgressBar();
    }

    /**
     * 设置右边按钮的文字
     *
     * @param resid 资源
     */
    public void setRightBtnText(int resid) {
        titleBar.setRightBtnText(resid);
    }

    /**
     * 设置右边按钮是否可点击
     *
     * @param enable 布尔类型
     */
    public void setRightBtnEnable(boolean enable) {
        titleBar.setRightBtnEnable(enable);
    }

    /**
     * 设置右边按钮的监听
     *
     * @param listener 事件
     */
    public void setRightBtnListener(ViewOnClickListener listener) {
        titleBar.setRightBtnListener(listener);
    }

    /**
     * 设置右边按钮的监听
     *
     * @param listener 事件
     */
    public void setImgRightBtnListener(ViewOnClickListener listener) {
        titleBar.setImgRightBtnListener(listener);
    }


    /**
     * 设置右边按钮的背景
     *
     * @param drawable 背景drawable
     */
    public void setRightBtnBG(Drawable drawable) {
        titleBar.setRightBtnBG(drawable);
    }

    /**
     * 设置右边按钮的背景
     *
     * @param resId 资源
     */
    public void setRightBtnBG(int resId) {
        titleBar.setRightBtnBG(resId);
    }

    public void setRightBtnTextAndRightDrawable(String text, int rightDrawable) {
        titleBar.setRightBtnTextAndRightDrawable(text, rightDrawable);
    }

    /**
     * 设置右边按钮的图标
     *
     * @param resId 资源
     */
    public void setImgRightBtn(int resId) {
        titleBar.setImgRightBtn(resId);
    }

    /**
     * 设置标题栏的背景
     *
     * @param drawable
     */
    public void setTitleBarBg(Drawable drawable) {
        titleBar.setTitleBarBg(drawable);
    }

    /**
     * 设置标题栏的背景
     *
     * @param resId
     */
    public void setTitleBarBg(int resId) {
        titleBar.setTitleBarBg(resId);
    }

    /**
     * 设置标题栏的背景颜色
     *
     * @param colorId
     */
    public void setTitleBarColor(int colorId) {
        titleBar.setTitleBarColor(colorId);
    }

    @Override
    public void setRightBtnText(String text) {
        titleBar.setRightBtnText(text);
    }

    public void setRightSpannaText(SpannableString sps) {
        titleBar.setRightSpannaText(sps);
    }

    /**
     * 设置标题的字体颜色及大小
     *
     * @param colorId
     * @param size    0为默认
     */
    public void setTitleStyle(int colorId, int size) {
        titleBar.setTitleStyle(colorId, size);
    }

    /**
     * 显示右边按钮
     */
    public void showRightBtn() {
        titleBar.showRightBtn();
    }

    /**
     * 隐藏右边按钮
     */
    public void hideRightBtn() {
        titleBar.hideRightBtn();
    }

    public void hideRightImgBtn() {
        titleBar.hideRightImgBtn();
    }

    /**
     * 隐藏软件盘
     *
     * @param view 焦点控件
     */
    protected void hideSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 显示软件盘
     *
     * @param view 焦点控件
     */
    protected void showSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);
    }

    /**
     * 获取返回布局ID
     *
     * @return 返回布局ID
     */
    public int getLeftId() {
        return titleBar.getLeftId();
    }

    /**
     * 获取title布局ID
     *
     * @return title布局ID
     */
    public int getCenterId() {
        return titleBar.getCenterId();
    }

    /**
     * 获取右边布局ID
     *
     * @return 右边布局ID
     */
    public int getRightId() {
        return titleBar.getRightId();
    }

    /**
     * 获取titleBar
     *
     * @return titleBar
     */
    public View getTitleBar() {
        return titleBar;
    }

    /**
     * 隐藏右边的提示数字。
     */
    public void hideRightIndicateText() {
        titleBar.hideRightIndicateText();
    }

    /**
     * 显示右边的提示数字
     */
    public void showRightIndicateText() {
        titleBar.showRightIndicateText();
    }

    /**
     * 设置右边的提示数字
     *
     * @param conut 数字
     */
    public void setIndicateText(int conut) {
        titleBar.setIndicateText(conut);
    }

    public ActivityInfo getActivityInfo() {
        if (actInfo != null) {
            return actInfo;
        } else {
            initActivityInfo();
            return actInfo;
        }
    }

    /**
     * 初始化布局文件
     */
    private void initContentView() {
        titleBar = (TitleBar) findViewById(R.id.activity_base_titlebar);
        mainContainer = (FrameLayout) findViewById(R.id.activity_base_content);
        ll_loading = (LinearLayout) mainContainer.findViewById(R.id.ll_loading);
        try {
            LayoutInflater.from(this).inflate(setView(), mainContainer);
        } catch (InflateException inflateException) {

        }
    }

    /**
     * 初始化acitivity信息
     */
    private void initActivityInfo() {
        actInfo = new ActivityInfo(this, tag);
        actInfo.setNeedActivityAniamtion(isNeedLowerActivityAniamtion);
    }

    /**
     * 向activityManager中添加activity
     */
    private void addActivity() {
        BaseActivityManager.getInstance().addActivity(actInfo);
    }

    /**
     * 从activityManager中移除activity
     */
    private void removeActivity() {
        BaseActivityManager.getInstance().removeActivity(actInfo);
    }

    /**
     * 在oncreate之前调用此方法
     */
    protected void preCreate() {
    }

    /**
     * 吐丝显示错误信息(方块)
     *
     * @param resId 字符串资源id
     */
    public void showToastError(int resId) {
        ToastUtil.INSTANCE.toastCenterError(resId);
    }

    /**
     * 长方形系统默认的style吐司，居中显示。
     *
     * @param msg
     */
    public void toastInCenter(String msg) {
        ToastUtil.INSTANCE.toastCenterError(msg);

    }

    private ToastTopDialog mToastTopDialog;

    public void toastInTop(String msg) {
//
//        mToastTopDialog = new ToastTopDialog(this, msg);
//        mToastTopDialog.show();

        showTopHintDialog(this, msg, 0);
//
//        Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
//        LinearLayout linearLayout = (LinearLayout) toast.getView();
//        linearLayout.setBackgroundResource(R.drawable.toast_bg);
//        TextView textView = (TextView) linearLayout.findViewById(com.android.internal.R.id.message);
//        textView.setTextColor(getResources().getColor(R.color.white));
////        if (linearLayout.getChildCount() > 0) {//魅族手机toast里面的text有默认的颜色，所以要给里面的text指定颜色。
////            for (int i = 0; i < linearLayout.getChildCount(); i++) {
////                View childView = linearLayout.getChildAt(i);
//////                childView.setBackgroundResource(R.drawable.toast_bg);
////            }
////        }
//        toast.setView(linearLayout);
//        toast.setGravity(Gravity.TOP, 0, 200);
//        toast.show();
    }

    public void showTopHintDialog(Context context, String topHintMsg, int topOffset) {

        mToastTopDialog = new ToastTopDialog(context, topHintMsg);
        // dialog.setTitle("操作提醒");
        Window dialogWindow = mToastTopDialog.getWindow();
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        WindowManager.LayoutParams params = mToastTopDialog.getWindow().getAttributes();
        if (topOffset > 0) {
            params.y = dip2px(context, topOffset);
        } else {
            //45 是标题栏高度，在标题栏下面
            params.y = dip2px(context, 100);
        }
        params.x = 0;
        dialogWindow.setAttributes(params);
        mToastTopDialog.setCanceledOnTouchOutside(true); //点击dialog区域之外的地方，dialog消失
        mToastTopDialog.show();

        mBaseHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != mToastTopDialog && mToastTopDialog.isShowing()) {
                    mToastTopDialog.dismiss();
                }
            }
        }, 1000);
    }


    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * px转dip
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 吐丝显示错误信息(方块)
     *
     * @param msg 字符串
     */
    public void showToastError(String msg) {
        ToastUtil.INSTANCE.toastCenterError(msg);
    }


    /**
     * 吐丝显示错误信息(方块)
     *
     * @param errorCode 字符串
     */
    public void showToastError(int errorCode, Object data) {
        ToastUtil.INSTANCE.toastCenterErrorWithErrorCode(String.valueOf(data), errorCode);

    }

    /**
     * 吐丝显示成功信息(方块)
     *
     * @param resId 字符串资源id
     */
    public void showToastSuccess(int resId) {
        ToastUtil.INSTANCE.toastCenterSuccess(resId);

    }

    /**
     * 吐丝显示成功信息(方块)
     *
     * @param msg 字符串
     */
    public void showToastSuccess(String msg) {
        ToastUtil.INSTANCE.toastCenterSuccess(msg);

    }

    /**
     * 吐丝显示提示信息(方块)
     *
     * @param resId 字符串资源id
     */
    public void showToastAlert(int resId) {
        CWToast.makeText(this, resId, Toast.LENGTH_LONG, true)
                .setToastType(CWToast.TOAST_TYPE_ALERT).show();
    }

    /**
     * 吐丝显示提示信息(方块)
     *
     * @param msg 字符串
     */
    public void showToastAlert(String msg) {
        CWToast.makeText(this, msg, Toast.LENGTH_LONG, true)
                .setToastType(CWToast.TOAST_TYPE_ALERT).show();
    }

    /**
     * 设置activity的布局文件
     *
     * @return 布局文件的resId
     */
    protected abstract int setView();

    /**
     * 获取界面元素
     */
    protected abstract void findViews();

    /**
     * 设置事件
     */
    protected abstract void initEvent();

    /**
     * 对象的初始化工作
     */
    protected abstract void init();

    /**
     * 加载数据
     */
    protected abstract void loadData();

    /**
     * <span style="color='red'">此方法不可用，界面跳转必须使用{@link BaseJumpManager} </span>
     *
     * @param intent Intent
     */
    public void startActivity(Intent intent) {
        if (checkSource(intent)) {
            super.startActivity(intent);
        }
    }

    /**
     * <span style="color='red'">此方法不可用，界面跳转必须使用{@link BaseJumpManager} </span>
     *
     * @param intent      Intent
     * @param requestCode 请求码
     */
    public void startActivityForResult(Intent intent, int requestCode) {
        if (checkSource(intent)) {
            super.startActivityForResult(intent, requestCode);
        }
    }

    /**
     * <span style="color='red'">此方法不可用，界面跳转必须使用{@link BaseJumpManager} </span>
     *
     * @param child       Activity
     * @param intent      Intent
     * @param requestCode 请求码
     */
    public void startActivityFromChild(Activity child, Intent intent,
                                       int requestCode) {
        if (checkSource(intent)) {
            super.startActivityFromChild(child, intent, requestCode);
        }
    }

    /**
     * <span style="color='red'">此方法不可用，界面跳转必须使用{@link BaseJumpManager} </span>
     *
     * @param intent      Intent
     * @param requestCode 请求码
     * @return IfNeeded
     */
    public boolean startActivityIfNeeded(Intent intent, int requestCode) {
        if (checkSource(intent)) {
            return super.startActivityIfNeeded(intent, requestCode);
        }
        return false;
    }

    /**
     * 检查activity的启动源
     *
     * @param intent 启动intent
     * @return 是否是正确来源
     */
    private boolean checkSource(Intent intent) {
        if (valideSource) {
            boolean rs = intent
                    .getBooleanExtra(BaseJumpManager.INTENT_FLAG_SOURCE, false);
            if (!rs) {
                Log.e("debug", "activity启动来源不正确，请使用ActivityJumpManager");
            }
            return rs;
        }
        return true;
    }

    protected void checkUpdate() {
        if (BaseApplication.getInstance().isVersionUpdate) {
            return;
        }
        CWUpdate update = new CWUpdate(this, EAction.getUpgradeUrl(),
                new CWUpdate.Callback() {
                    @Override
                    public void excuteSelfMethod() {

                    }

                    @Override
                    public void excuteSelfMethod(Object... obj) {
                        if (obj.length > 1) {
                            if ((obj[1] + "")
                                    .equals(CWUpdate.UPDATE_FLAT_DOWNLAOD_APK_ERROR
                                            + "")) {
                                CWToast.makeText(BaseActivity.this,
                                        R.string.download_apk_failed,
                                        Toast.LENGTH_LONG, true)
                                        .setToastType(CWToast.TOAST_TYPE_ERROR)
                                        .show();
                            }
                        }
                    }
                });
        update.excute(true);
    }

    /**
     * 点击事件
     *
     * @author RES-KUNZHU
     */
    private class OnClick extends ViewOnClickListener {

        @Override
        public void avertRepeatOnClick(View v) {
            if (v.getId() == titleBar.getLeftId()) {
                if (mGoBackListener != null) {
                    mGoBackListener.goBack();
                } else {
                    finish();
                }
            }
        }

    }


    /**
     * 确认关闭activity，动画完成的回调方法 {@inheritDoc}
     */
    @Override
    public void activityAnimationFinish() {

    }

    /**
     * 第一次打开activity，打开动画完成的回调方法
     */
    @Override
    public void activityAnimationComplete() {
    }

    /**
     * 放弃右滑关闭后，activity界面还原完成的回调方法
     */
    @Override
    public void activityAnimationReBack() {
    }

    /**
     * 右滑打开activity的瞬间，只回调一次，首次。
     */
    @Override
    public void activityAnimationFirstOpen() {
    }


    /**
     * 显示全屏进度条
     */
    public void showCricleProgress() {
        try {
            showCricleProgress(null);
        } catch (OutOfMemoryError error) {
            error.getStackTrace();
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    public void showLoadingView() {
        for (int i = 0; i < mainContainer.getChildCount(); i++) {
            mainContainer.getChildAt(i).setVisibility(View.GONE);
        }
        ll_loading.setVisibility(View.VISIBLE);
//        ImageView iv_loading = (ImageView) ll_loading.findViewById(R.id.iv_loading);
//        Animation animation = AnimationUtils.loadAnimation(this, R.anim.loading_anim);
//        iv_loading.setAnimation(animation);

    }

    public void hidenLoadingView() {
        for (int i = 0; i < mainContainer.getChildCount(); i++) {
            mainContainer.getChildAt(i).setVisibility(View.VISIBLE);
        }
        ll_loading.setVisibility(View.GONE);
    }

    /**
     * 显示全屏进度条
     *
     * @param msg
     */
    public void showCricleProgress(String msg) {

        if (progressBar == null) {
            progressBar = new NewCWProgressBar(this);
            progressBar.setCanceledOnTouchOutside(false);
            progressBar.setCancelable(true);
        }
        if (!isFinishing()) {
            if (!TextUtils.isEmpty(msg)) {
                progressBar.setMessage(msg);
            }
            if (!progressBar.isShowing()) {
                progressBar.show();
            }
        }

        if (null != mOnDismissListener) {
            progressBar.setOnDismissListener(mOnDismissListener);
        }

    }

    DialogInterface.OnDismissListener mOnDismissListener;

    public void setCricleProgressOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        mOnDismissListener = onDismissListener;
    }


    /**
     * 显示全屏进度条
     *
     * @param resId
     */
    public void showCricleProgress(int resId) {
        showCricleProgress(getString(resId));
    }

    /**
     * 关闭全屏进度条
     */
    public void hideCricleProgress() {
        if (progressBar != null && !isFinishing() && progressBar.isShowing()) {
            progressBar.dismiss();
        }
    }


    public void showDownloadProgress() {
        showDownloadProgress("");
    }


    public DownloadProgressBar mDownloadProgressBar;

    /**
     * 显示下载全屏进度条
     */
    public void showDownloadProgress(String msg) {

        if (mDownloadProgressBar == null) {
            mDownloadProgressBar = new DownloadProgressBar(this);
            mDownloadProgressBar.setCanceledOnTouchOutside(false);
            mDownloadProgressBar.setCancelable(true);
        }
        if (!isFinishing()) {
            if (!TextUtils.isEmpty(msg)) {
                mDownloadProgressBar.setMessage(msg);
            }
            if (!isDownloadProessBarShowing()) {
                mDownloadProgressBar.setCancelable(false);
                mDownloadProgressBar.hideProgressBar();
                mDownloadProgressBar.show();
            }
        }


        if (null != mDownloadProgressOnDismissListener) {
            mDownloadProgressBar.setOnDownLoadDialogDismissListener(mDownloadProgressOnDismissListener);
        }

    }


    /**
     * 关闭下载全屏进度条
     */
    public void hideDownloadProgress() {
        if (mDownloadProgressBar != null && !isFinishing() && isDownloadProessBarShowing()) {
            mDownloadProgressBar.dismiss();
        }
        //取消按钮默认不显示
        hideCancelButtonOfDownloadProgress();
    }

    public boolean isDownloadProessBarShowing() {
        if (mDownloadProgressBar != null) {
            return mDownloadProgressBar.isShowing();
        }
        return false;
    }

    /**
     * 取消按钮隐藏
     */
    public void hideCancelButtonOfDownloadProgress() {
        try {
            if (mDownloadProgressBar != null) {
                mDownloadProgressBar.getCancelButton().setVisibility(View.INVISIBLE);
                mDownloadProgressBar.setCancelable(false);
                mDownloadProgressBar.hideProgressBar();
            }
        } catch (Exception e) {

        }

    }

    /**
     * 取消按钮显示
     */
    public void showCancelButtonOfDownloadProgress() {
        if (mDownloadProgressBar != null && isDownloadProessBarShowing()) {
            mDownloadProgressBar.getCancelButton().setVisibility(View.VISIBLE);
            mDownloadProgressBar.setCancelable(true);
        }
    }

    DownloadProgressBar.OnDownLoadDialogDismissListener mDownloadProgressOnDismissListener;

    public void setDownloadProgressOnDismissListener(DownloadProgressBar.OnDownLoadDialogDismissListener onDismissListener) {
        mDownloadProgressOnDismissListener = onDismissListener;
    }

    public void updateDownloadProgress(int progress) {
        if (mDownloadProgressBar != null && !isFinishing()) {
            mDownloadProgressBar.updateDownloadProgress(progress);
        }
    }

    public void hideDownloadHorizontalProgressBar() {
        if (mDownloadProgressBar != null && !isFinishing()) {
            mDownloadProgressBar.hideProgressBar();
        }
    }

    public boolean isTopActivity() {
        try {
            if (getClass().getName().equals(BaseActivityManager.getInstance().getTopClassNameInApp())) {
                return true;
            }
        } catch (Exception e) {
        }

        return false;
    }

    public boolean isContainActivity(Class clazz) {
        try {
            return BaseActivityManager.getInstance().isContainsActivityInStack(clazz);
        } catch (Exception e) {
        }

        return false;
    }

    private HomeListener mHomeWatcher;

    /**
     * Home键监听
     */
    protected void registListenerHome() {
        mHomeWatcher = new HomeListener(this);
        mHomeWatcher.setOnHomePressedListener(new HomeListener.OnHomePressedListener() {
            @Override
            public void onHomePressed() {
                if (BaseApplication.getInstance().isEyeGuardModeOpen) {
                    EyeGuardModeView.showEyeGuard(false);
                }

                BaseActivity.this.onHomeKeyPressed();
            }

            @Override
            public void onHomeLongPressed() {
                if (BaseApplication.getInstance().isEyeGuardModeOpen) {
                    EyeGuardModeView.showEyeGuard(false);
                }
                BaseActivity.this.onHomeKeyLongPressed();
            }
        });
        mHomeWatcher.startWatch();
    }

    public void onHomeKeyPressed() {
    }

    public void onHomeKeyLongPressed() {
    }

    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        Configuration configuration = res.getConfiguration();
        configuration.fontScale = (float) (0.875 + 0.125 * BaseApplication.getInstance().mFontSizeScale);
        res.updateConfiguration(configuration, res.getDisplayMetrics());
        return res;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                View view = getCurrentFocus();
                hideKeyboard(ev, view, BaseActivity.this);//调用方法判断是否需要隐藏键盘
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideKeyboard(MotionEvent event, View view,
                             Activity activity) {
        try {
            if (view != null && view instanceof EditText) {
                int[] location = {0, 0};
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + view.getWidth(), bootom = top + view.getHeight();
                // 判断焦点位置坐标是否在空间内，如果位置在控件外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right
                        || event.getY() < top || event.getRawY() > bootom) {
                    // 隐藏键盘
                    IBinder token = view.getWindowToken();
                    InputMethodManager inputMethodManager = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        inputMethodManager.hideSoftInputFromWindow(token,
                                InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            Log.e(TAG, "setRequestedOrientation: " + "avoid calling setRequestedOrientation when Oreo.");
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = android.content.pm.ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            android.content.pm.ActivityInfo o = (android.content.pm.ActivityInfo) field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
